﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;

using Ext.Net;
using ProjectName.Data;
using ProjectName.Service;
using Kwan.Helper.Bitmaps;
using Kwan.Data;

namespace ProjectName.Web.Admin.TableName
{
    public partial class Default : UIPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                BtnAddClassInfo.Hidden = !permit[0];
                AppendChild.Hidden = !permit[0];
                BtnAddInfo.Hidden = !permit[0];
                Rename.Hidden = !permit[2];
                //btnChangeHot.Hidden = !permit[2];

                BtnDeleteInfo.Hidden = !permit[3];
                Remove.Hidden = !permit[3];
                if (permit[3])
                {
                    List<GridCommand> gridCommand = new List<GridCommand>{
                        ExtHelper.CreateGridCommand("Delete", Icon.Delete, "删除", "删除该条记录")
                    };
                    GridPanel1.ColumnModel.Columns.Add(ExtHelper.CreateCommandColumn(gridCommand));
                }
                //ResourceManager1.RegisterIcon(Icon.Image);
            }
        }

        protected void BtnAddInfo_Click(object sender, EventArgs e)
        {
            SetEditWindow(new TTableName());
            EditWindow.Show();
        }

        [DirectMethod]
        public void DeleteSelected(string obj)
        {
            string[] list = obj.Split(',');
            (TTableName.entityID == list).Delete<TTableName>();
            Store1.DataBind();
        }

        [DirectMethod]
        public void ChangeState(string obj, string NameValue)
        {
            IList<TTableName> list = JSON.Deserialize<IList<TTableName>>(obj);
            if (list.Count > 0)
            {
                CrudManage.ChangeState(list, NameValue);
                Store1.DataBind();
            }
            else
            {
                ExtHelper.GetNotification("系统提示", "请至少选择一项！").Show();
            }
        }

        [DirectMethod]
        public void EditInfo(string EntityID)
        {
            if (!permit[2]) return;
            SetEditWindow((TTableName.entityID == int.Parse(EntityID)).ListFirst<TTableName>());
            EditWindow.Show();
        }

        protected void RefreshDS(object sender, StoreRefreshDataEventArgs e)
        {
            NameValueCollection ps = new NameValueCollection();
            ps.Set("gridsort", e.Sort);
            ps.Set("dir", e.Dir.ToString());
            
            //搜索项
            ps.Set("Cid", txtFilter.Text);
            ps.Set("tag", txtSearch.Text);

            int pageindex = e.Start / e.Limit;
            Kwan.Data.Region r = new Kwan.Data.Region(pageindex, e.Limit);

            Expression exp = TableNameQuery.MakeSearchWhere(ps);
            IList<TTableName> ListView = exp.List<TTableName>(r, new string[] { e.Sort + " " + e.Dir });

            e.Total = new Expression().Count<TTableName>();
            Store1.DataSource = ListView;
            Store1.DataBind();
        }

        protected void SetEditWindow(TTableName tt)
        {
            txtID.Text = tt.EntityID.ToString();
            txtEnable.Checked = tt.Enable;
            txtHot.Checked = tt.Hot;;ExtSetInfo
        }

        protected void SaveEditWindow(object sender, DirectEventArgs e)
        {
            TTableName tt = Convert.ToInt32(txtID.Text) > 0 ? 
                (TTableName.entityID == Convert.ToInt32(txtID.Text)).ListFirst<TTableName>() : new TTableName();
ExtSaveInfo
            tt.Enable = txtEnable.Checked;
            tt.Hot = txtHot.Checked;

            DBContext.Save(tt);
            Store1.DataBind();
            Store1.Dispose();
            EditWindow.Hide();
        }

        [DirectMethod]
        public void InitClassInfo(string EntityID)
        {
            EntityID = string.IsNullOrEmpty(EntityID) ? "0" : EntityID;
            TTableNameClass tt = new TTableNameClass();
            tt.Pid = Convert.ToInt32(EntityID);
            SetClass(tt);
            ClassWindow.Show();
        }

        [DirectMethod]
        public void SetClassInfo(string EntityID)
        {
            TTableNameClass tt = DBContext.Load<TTableNameClass>(Convert.ToInt32(EntityID));
            SetClass(tt);
            ClassWindow.Show();
        }

        private void SetClass(TTableNameClass tt)
        {
            txtClassID.Text = tt.EntityID.ToString().ToString();
            txtClassNameCN.Text = tt.NameCN;
            txtClassNameEN.Text = tt.NameEN;
            txtClassPid.Text = tt.Pid.ToString();
            txtClassSort.Text = tt.Sort.ToString();
        }

        protected void SaveClassForm(object sender, EventArgs e)
        {
            string x = txtClassPid.Text;
            TTableNameClass tt = Convert.ToInt32(txtClassID.Text) == 0 ? new TTableNameClass() : 
                (TTableNameClass.entityID == Convert.ToInt32(txtClassID.Text)).ListFirst<TTableNameClass>();
            tt.NameCN = txtClassNameCN.Text;
            tt.NameEN = txtClassNameEN.Text;
            tt.Pid = string.IsNullOrEmpty(txtClassPid.Text) ? 0 : int.Parse(txtClassPid.Text);
            tt.Sort = Convert.ToInt32(txtClassSort.Text);
            DBContext.Save(tt);
            ClassWindow.Hide();
            RefreshTree();
        }

        protected void GetExamplesNodes(object sender, NodeLoadEventArgs e)
        {
            if (e.NodeID == "root")
            {
                IList<TTableNameClass> ClassList = new Expression().List<TTableNameClass>();
                if (ClassList.Count > 0)
                {
                    IList<TTableNameClass> Parent = ClassList.AsQueryable().Where(a => a.Pid == 0).ToList(); //父节点
                    e.Nodes = CreateTree(ClassList, Parent);
                }

            }
        }

        private TreeNodeCollection CreateTree(IList<TTableNameClass> list, IList<TTableNameClass> Parent)
        {
            TreeNodeCollection nodes = new TreeNodeCollection(false);
            foreach (TTableNameClass t in Parent)
            {
                TreeNode node = new TreeNode();
                node.Icon = Icon.Report;
                IList<TTableNameClass> child = list.AsQueryable().Where(a => a.Pid == t.EntityID).ToList();
                if (child.Count > 0)
                {
                    node.NodeID = t.EntityID.ToString();
                    node.Text = t.NameCN;
                    //node.SingleClickExpand = true;
                    node.Nodes.AddRange(CreateTree(list, child));
                }
                else
                {
                    node.NodeID = t.EntityID.ToString();
                    node.Text = t.NameCN;
                    node.Leaf = true;
                    //node.SingleClickExpand = true;
                }
                nodes.Add(node);
            }
            return nodes;
        }

        protected void RemoteRename(object sender, RemoteRenameEventArgs e)
        {
            e.Accept = true;
            TTableNameClass tt = (TTableNameClass.entityID == Convert.ToInt32(e.NodeID)).ListFirst<TTableNameClass>();
            tt.NameCN = e.NewText;
            DBContext.Save(tt);
        }

        protected void RemoteRemove(object sender, RemoteActionEventArgs e)
        {
            TTableName tt = (TTableName.cid == Convert.ToInt32(e.NodeID)).ListFirst<TTableName>();
            if (tt != null)
            {
                X.Msg.Alert("系统提示", "不能删除有内容的类别！").Show();
            }
            else
            {
                e.Accept = true;
                (TTableNameClass.entityID == nodeID).Delete<TTableNameClass>();
            }
        }

        protected void RemoteAppend(object sender, RemoteAppendEventArgs e)
        {
            e.Accept = true;
            TTableNameClass tt = new TTableNameClass();
            tt.NameCN = e.Text;
            tt.Pid = int.Parse(e.ParentNodeID);
            DBContext.Save(tt);
        }

        protected void RemoteMove(object sender, RemoteMoveEventArgs e)
        {
            e.Accept = true;
            (TTableNameClass.entityID == Convert.ToInt32(e.NodeID))
                .Edit<TTableNameClass>(d => { d.Pid = int.Parse(e.TargetNodeID); });
        }
        [DirectMethod]
        public void RefreshTree()
        {
            txtFilter.Text = "";
            ClassTree.ReloadAsyncNode("root", new JFunction());
            ClassTree.ExpandAll();
            EWTree.ReloadAsyncNode("root", new JFunction());
            EWTree.ExpandAll();
        }

        [DirectMethod]
        public string UploadNews(string EntityID)
        {
            string msg = string.Empty;
            using (Cutter imgCutter = new Cutter())
            {
                imgCutter.DefPath = "Upload\\News\\";
                imgCutter.WidthArray = new int[] { 950 };
                imgCutter.HeightArray = new int[] { 713 };
                imgCutter.PathArray = new string[] { "pNews" };
                msg = imgCutter.UploadImage(txtFileUpload.FileContent, string.Empty);
                //msg = "{'success':true,'url':'/Upload/News/pNews/" + FileName + "'}";
            }
            return "/Upload/News/pNews/" + msg;
        }
    }
}